package com.atguigu.crowd.mvc.handler;

import com.atguigu.crowd.entity.Menu;
import com.atguigu.crowd.service.MenuService;
import com.atguigu.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

/**
 * @author yzt
 * @create 2021-09-13 11:35
 */
//@Controller
@RestController  //ResponseBody 和 Controller 结合体
public class MenuHandler {

    @Autowired
    private MenuService menuService;

//    @ResponseBody
    @RequestMapping("/menu/get/whole/tree")
    public ResultEntity<Menu> getWholeTree(){
        List<Menu> menuList = menuService.getAll();
        //创建根节点
        Menu root = new Menu();
        //创建 Map 对象用来存储 id 和 Menu 对象的对应关系便于查找父节点
        HashMap<Integer, Menu> menuHashMap = new HashMap<>();
        // 4.遍历 menuList 填充 menuMap
        for(Menu menu : menuList){
            Integer id = menu.getId();
            menuHashMap.put(id,menu);
        }
        //5.再次遍历 menuList 查找根节点、组装父子节点
        for(Menu menu : menuList){
            Integer pid = menu.getPid();
            if(pid == null){
                root = menu;
                continue;
            }
            // 9.如果 pid 不为 null，说明当前节点有父节点，那么可以根据 pid 到 menuMap 中 查找对应的 Menu 对象
            Menu father = menuHashMap.get(pid);
            // 10.将当前节点存入父节点的 children 集合
            father.getChildren().add(menu);
        }
        return ResultEntity.successWithData(root);
    }

//    @ResponseBody
    @RequestMapping("/menu/save")
    public ResultEntity<String> menuSave(Menu menu){
        menuService.saveMenu(menu);
        return ResultEntity.successWithoutData();
    }

//    @ResponseBody
    @RequestMapping("/menu/edit")
    public ResultEntity<String> menuEdit(Menu menu){
        menuService.editMenu(menu);
        return ResultEntity.successWithoutData();
    }

//    @ResponseBody
    @RequestMapping("/menu/remove")
    public ResultEntity<String> menuRemove(@RequestParam("id") Integer id){
        menuService.removeMenu(id);
        return ResultEntity.successWithoutData();
    }
}
